package com.slkj.shilixiaoyuanapp.ui.teacher.tool.PunchClock;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.api.InjectParam;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.KqSsDetailEntity;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.leave.AplyyLeaveActivity;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TestDataProvider;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.StateLayout;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.w3c.dom.Text;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_kq_ss, title = "申诉")
public class KqSsActivity extends BaseActivity {
    @InjectParam int id;
    @InjectParam String info;
    @InjectParam String ycState;
    @InjectParam String time;
    @InjectParam int  fromType;//1:打卡历史 ：2：消息列表:3我的审批

    @BindView(R.id.tv_ycqk)
    TextView tvYcqk;
    @BindView(R.id.statelayout)
    StateLayout stateLayout;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    @BindView(R.id.tv_up)
    TextView tvUp;
    @BindView(R.id.tv_remark)
    TextView tv_remark;
    @BindView(R.id.view_remark)
    View view_remark;
    @BindView(R.id.iv_select_img)
    ImageView iv_select_img;
    @BindView(R.id.iv_seiect_spr)
    ImageView iv_seiect_spr;
    @BindView(R.id.layout_chose_pic)
    RelativeLayout layout_chose_pic;
    @BindView(R.id.layout_chose_spr)
    RelativeLayout layout_chose_spr;

    public static final String tag = "KqSsActivity";
    ChosePicAdapter adapter;
    ArrayList<String> picPaths = new ArrayList<>();
    public TakePictureUtils takePictureUtils;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<PeopleEntity> peopleEntities = new ArrayList<>();
    @Override
    protected void init() {
        KqSsActivity__JumpCenter.bind(this);
        RxEventProcessor.get().bind(this);
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths, this);
        recycerPic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }
            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
        if (fromType == 1) {
            tvYcqk.setText(ycState);
            tvTime.setText(time);
            if (info.equals("申诉")) {
                stateLayout.showContentView();
            } else {
                stateLayout.showLoadingView();
                iv_select_img.setVisibility(View.GONE);
                iv_seiect_spr.setVisibility(View.GONE);
                editContent.setFocusable(false);
                layout_chose_pic.setClickable(false);
                layout_chose_spr.setClickable(false);
                HttpHeper.get().toolService()
                        .getKqSsDetail(id)
                        .compose(getThread())
                        .compose(bindToLifecycle())
                        .subscribe(new CommonCallBack<KqSsDetailEntity>(stateLayout) {
                            @Override
                            public void onCallBackSuccess(KqSsDetailEntity data) {
                                //填充数据
                                editContent.setText(data.getReason());
                                if (data.getImages() != null && !data.getImages().isEmpty()) {
                                    recycerPic.setLayoutManager(new GridLayoutManager(KqSsActivity.this, CHOSE_PIC_SPAN_COUNT));
                                    adapter = new ChosePicAdapter(data.getImages(), KqSsActivity.this, false);
                                    recycerPic.setAdapter(adapter);
                                }
                                tvSpr.setText(ChosePeopleActivity.getPeoplesInfos(data.getAuditor()));
                                view_remark.setVisibility(data.getState() == 1?View.VISIBLE:View.GONE);
                                tv_remark.setText(data.getReason());
                            }
                        });
                tvUp.setVisibility(View.GONE);
            }

        } else {
            iv_select_img.setVisibility(View.GONE);
            iv_seiect_spr.setVisibility(View.GONE);
            editContent.setFocusable(false);
            layout_chose_pic.setClickable(false);
            layout_chose_spr.setClickable(false);
            HttpHeper.get().toolService()
                    .getKqSsDetailByMessage(id)
                    .compose(getThread())
                    .compose(bindToLifecycle())
                    .subscribe(new CommonCallBack<KqSsDetailEntity>(stateLayout) {
                        @Override
                        public void onCallBackSuccess(KqSsDetailEntity data) {
                            //填充数据
                            tvYcqk.setText(data.getTitle());
                            tvTime.setText(data.getDatetime());
                            editContent.setText(data.getReason());
                            if (data.getImages() != null && !data.getImages().isEmpty()) {
                                recycerPic.setLayoutManager(new GridLayoutManager(KqSsActivity.this, CHOSE_PIC_SPAN_COUNT));
                                adapter = new ChosePicAdapter(data.getImages(), KqSsActivity.this, false);
                                recycerPic.setAdapter(adapter);
                            }
                            tvSpr.setText(ChosePeopleActivity.getPeoplesInfos(data.getAuditor()));
                            view_remark.setVisibility(data.getState() == 1 ? View.VISIBLE : View.GONE);
                            tv_remark.setText(data.getReason());
                        }
                    });
            tvUp.setVisibility(View.GONE);
        }
    }




    @OnClick(R.id.layout_chose_pic)
    public void onLayoutChosePicClicked() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                KqSsActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(KqSsActivity.this);
            }
        });
    }


    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().toolService().getCommonSpr(1)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<ArrayList<PeopleEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(ArrayList<PeopleEntity> data) {
                            peopleEntities.addAll(data);
                            ChosePeopleActivity__JumpCenter.builder(KqSsActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChosePeopleActivity__JumpCenter.builder(KqSsActivity.this).setTag(tag).setData(peopleEntities).create().go();
        }

    }

    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<PeopleEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }
    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        KqSsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
    @OnClick(R.id.tv_up)
    void upData() {
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入会议内容");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }
        UpdataFileUtil.UpImgObservable("appeal", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        String img = StringUtils.listToString(result);
                        return HttpHeper.get().toolService().addKqSs(id, context, sqrIds.toString(),img,ycState);
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(KqSsActivity.this,data);
                        clearContent();
                    }
                });
    }
}
